<template>
   <div class="bar" ref="normal" @click="btnClick">
          <div class="bar-inner" >
            <div class="color-process" ref="color"></div>
            <div class="process-btn" ref="btn" @touchstart.prevent="btnTouchStart" @touchmove.prevent="btnTouchMove" @ @touchend="btnTouchEnd"></div>
          </div>
        </div>
</template>

<script type="text/ecmascript-6">
const BTN_WIDTH=16;
export default{
  name:'',
  props:{
  	percent:{
  		type:Number,
  		default:0
  	}
  },
  watch:{
		// 监听 percent newval 判断新值
  	percent(newval){
  		if(newval>=0&&!this.touch.initiated){
  			const barWidth=this.$refs.normal.clientWidth-BTN_WIDTH;
  			const offsetWidth=newval*barWidth;
  			this._offset(offsetWidth)
  		}
  	}
  },
  created(){
this.touch={}
  },
  methods:{
		// btn  点击start
  	btnTouchStart(e){
  		this.touch.initiated=true;
  		this.touch.startX=e.touches[0].pageX;
  		this.touch.left=this.$refs.color.clientWidth;
		},
		// btn  点击moving
  	btnTouchMove(e){
  		if(!this.touch.initiated){
  			return
  		};
  		const deltaX=e.touches[0].pageX-this.touch.startX;
  		const offsetWidth=Math.min(Math.max(0,this.touch.left+deltaX),this.$refs.normal.clientWidth-BTN_WIDTH);
  		this._offset(offsetWidth)
		},
		// btn  添加停止
  	btnTouchEnd(e){
  	this.touch.initiated=false;
  	this._changetime()
		},
		// btn 点击事件
  	btnClick(e){
  		const rect=this.$refs.normal.getBoundingClientRect();
  		const offsetWidth=e.pageX-rect.left;
  		this._offset(offsetWidth);
  		this._changetime()
		},
		// 计算 percent
  	_changetime(){
  	const barWidth=this.$refs.normal.clientWidth-BTN_WIDTH;
  	const percent=this.$refs.color.clientWidth/barWidth;
  	this.$emit('changePercent',percent)
		},
		// 延时修改 
  	_offset(offsetWidth){
  		this.$refs.color.style.width=`${offsetWidth}px`;
  		this.$refs.btn.style['transform']=`translate3d(${offsetWidth}px,0,0)`
  	}
  },
  data(){ return{}},
  components:{}
}
</script>

<style rel="stylesheet" lang="less">
  .bar{
    height: 30px;
  }
  .bar-inner{
    position: relative;
    top: 13px;
    height: 4px;
    background-color: rgba(0,0,0,0.3)
  }
  .color-process{
    position: absolute;
    height: 100%;
    background-color: #ffcd32;
  }
  .process-btn{
    position: absolute;
    top: -6px;
    width: 16px;
    height: 16px;
    border-radius: 50%;
    box-sizing: border-box;
    border: 3px solid #fff;
    background-color: #ffcd32;
  }
</style>
